<template>
  <view class="MemberDetail">
    <cu-form ref="studentForm" v-if="type === 'student'">

      <view class="form-group">
        <cu-input disabled name="STUDENTNAME" title="真实姓名" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-input disabled type="number" name="STUDENTNO" title="学号" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-input disabled type="idcard" name="SFZNO" title="身份证号" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-input disabled maxlength="11" type="number" name="PHONENO" title="联系电话" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-input disabled name="ADDR" title="现住址" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-radio disabled name="SEX" title="性别" :options="sexOpt"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-input disabled name="LXR" title="联系人" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-input disabled type="number" name="LXR_PHONENO" title="联系人电话" required placeholder="无"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-picker placeholder="无" disabled name="ZZMM" title="政治面貌" required :options="ZZMMOpts"/>
      </view>

      <view class="form-group">
        <cu-picker placeholder="无" disabled name="WHCD" title="文化程度" required :options="WHCDOpts"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-input disabled name="YDW" title="原单位" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-input disabled name="YZW" title="原职位" required placeholder="无"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-uploader disabled name="PICID" required title="个人照片"/>
      </view>
	<view class="flex justify-center">
		<view v-if="can(5)" class="margin-top">
		  <picker :range="roleOpts" range-key="label" :value="curSelectRoleIdx" @change="onRolePickChange" class="flex justify-center">
		    <button class="cu-btn round bg-red shadow">修改角色</button>
		  </picker>
		</view>
		<view class="margin-top" v-if="can(5)">
			<picker :range="UserState" range-key="label" :value="curSelectUserStateIdx" @change="onUserStatePickChange" class="flex justify-center">
			  <button class="cu-btn round bg-red shadow">修改状态</button>
			</picker>
		</view>
	</view>
    </cu-form>


    <cu-form ref="teacherForm" v-if="type === 'teacher'">
      <view class="form-group">
        <cu-input disabled name="TEACHERNAME" title="真实姓名" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-input disabled type="number" name="TEACHERNO" title="教师编号" required placeholder="无"/>
      </view>


      <view class="form-group">
        <cu-picker disabled name="MAJOR_ID" title="专业" :options="majorOpts" required placeholder="无"/>
      </view>

      <view class="form-group">
        <cu-input disabled name="PHONENO" title="联系电话" required placeholder="无"/>
      </view>

      <view class="form-group" v-if="memberData.SEX">
        <cu-radio disabled name="SEX" title="性别" :options="sexOpt" />
      </view>

      <view class="form-group" v-else>
        <view class="cu-form-group">
          <view class="title">性别</view>
          <input disabled/>
          <text>未知</text>
        </view>
      </view>
		<view class="flex justify-center">
			<view v-if="can(4)" class="margin-top">
			   <picker :range="roleOpts" range-key="label" :value="curSelectRoleIdx" @change="onRolePickChange" class="flex justify-center">
			     <button class="cu-btn round bg-red shadow">修改角色</button>
			   </picker>
			 </view>
			<view class="margin-top" v-if="can(4)">
				<picker :range="UserState" range-key="label" :value="curSelectUserStateIdx" @change="onUserStatePickChange" class="flex justify-center">
				  <button class="cu-btn round bg-red shadow">修改状态</button>
				</picker>
			</view>
		</view>.
		
    </cu-form>
  </view>
</template>

<script lang="ts" setup>
import CuInput from '../../components/cu-input/index.vue'
import CuRadio from '../../components/cu-radio/index.vue'
import CuPicker from '../../components/cu-picker/index.vue'
import CuForm from '../../components/cu-form/index.vue'
import CuUploader from '../../components/cu-uploader/index.vue'
import {onLoad} from "@dcloudio/uni-app";
import {computed, nextTick, onMounted, reactive, ref} from "vue";
import {MemberDetailStudentDAT, MemberDetailTeacherDAT} from "../../types/responseTypes";
import {ReactiveVariable} from "vue/macros";
import {useProfileArgs} from "../profile/useProfileArgs";
import {useMajorList} from "../profile/useMajorList";
import {usePermission} from "../../utils/usePermission";
import {modifyUserRole,modifyUserStatus} from "../../api/manage";
import {useStore} from "vuex";
import {useRoleOpts} from "./useRoleOpts";
interface CuPickerOpt {
  value: string
  label: string
}
const UserState = ref<any>([{value:"1",label:"启用"},{value:"0",label:"停用"}])
const curSelectUserStateIdx = ref<any>(-1)
function onUserStatePickChange(e){
	curSelectUserStateIdx.value = e.detail.value
	if(curSelectUserStateIdx.value>-1){
		uni.showModal({
		  title: '提示',
		  content: `您确定修改吗？`,
		  success: async ({confirm}) => {
		    if (confirm){
		      try {
		        const res = await modifyUserStatus({
		          CUSER_IDS: memberData.CUSER_ID + '',
		          STATE: UserState.value[curSelectUserStateIdx.value].value,
		          OPERATOR_ID: state.user.userInfo.CUSER_ID
		        })
		
		        if(res.ERROR[0].errcode == '0'){
		          uni.showToast({
		            title: '修改成功',
		            icon: 'success',
		            mask: true
		          })
		
		          setTimeout(() => {
		            uni.$emit('updateRole')
		            uni.navigateBack()
		          },500)
		        }else {
		          uni.showToast({
		            title: res.ERROR[0].error,
		            icon: 'none',
		            mask: true
		          })
		        }
		      }catch (err){
		        uni.showToast({
		          title: '修改状态异常',
		          icon: 'none',
		          mask: true
		        })
		      }
		
		    }
		  }
		})
	}
	
}
const {ZZMMOpts, WHCDOpts, sexOpt} = useProfileArgs([
  {
    CSNAME: '政治面貌',
    key: 'ZZMMOpts'
  },
  {
    CSNAME: '文化程度',
    key: 'WHCDOpts'
  },
  {
    CSNAME: '性别',
    key: 'sexOpt'
  }
]).opts

const {can} = usePermission()

let memberData = reactive({}) as ReactiveVariable<MemberDetailTeacherDAT | MemberDetailStudentDAT>
const type = ref<'teacher' | 'student' | ''>('')
onLoad((options: any) => {
  memberData =  JSON.parse(decodeURIComponent(options.info))
  type.value = memberData.hasOwnProperty('TEACHERNAME') ? 'teacher' : 'student'
  uni.setNavigationBarTitle({
    title: (type.value === 'teacher' ?
        (memberData as ReactiveVariable<MemberDetailTeacherDAT>).TEACHERNAME : (memberData as ReactiveVariable<MemberDetailStudentDAT>).STUDENTNAME)
    + '的个人资料'
  })
})
const teacherForm = ref<any>(null)
const studentForm = ref<any>(null)

const {majorOpts} = useMajorList()
function initTeacherData(){
  nextTick(() => {
    teacherForm.value.setFields(['TEACHERNAME','TEACHERNO','MAJOR_ID','PHONENO','SEX'].map(name => ({
      value: (memberData as MemberDetailTeacherDAT)[name as keyof MemberDetailTeacherDAT] || '',
      name
    })))
  })
}

function initStudentData(){
  nextTick(() => {
    studentForm.value.setFields(['STUDENTNAME','STUDENTNO','PICID','SFZNO','SEX','ADDR','PHONENO','LXR','LXR_PHONENO','ZZMM','WHCD','YDW','YZW'].map(name => ({
      value: (memberData as MemberDetailStudentDAT)[name as keyof MemberDetailStudentDAT] || '',
      name
    })))
  })
}

onMounted(() => {
  switch (type.value){
    case 'teacher':{
      initTeacherData()
      break
    }

    case 'student':{
      initStudentData()
      break
    }
  }
})
const {state} = useStore()
const {roleOpts} = useRoleOpts()
const curSelectRoleIdx = ref(-1)

function onRolePickChange(e: any){
  const idx = e.detail.value
  if (idx > -1){
    const name = type.value === 'teacher' ? (memberData as MemberDetailTeacherDAT).TEACHERNAME : (memberData as MemberDetailStudentDAT).STUDENTNAME
    uni.showModal({
      title: '提示',
      content: `确定要将 ${name} 的角色改为${roleOpts[idx].label}吗？\n`,
      success: async ({confirm}) => {
        if (confirm){
          try {
            const res = await modifyUserRole({
              CUSER_IDS: memberData.CUSER_ID + '',
              ROLE_ID: roleOpts[idx].value,
              OPERATOR_ID: state.user.userInfo.CUSER_ID
            })

            if(res.ERROR[0].errcode == '0'){
              uni.showToast({
                title: '修改成功',
                icon: 'success',
                mask: true
              })

              setTimeout(() => {
                uni.$emit('updateRole')
                uni.navigateBack()
              },500)
            }else {
              uni.showToast({
                title: res.ERROR[0].error,
                icon: 'none',
                mask: true
              })
            }
          }catch (err){
            uni.showToast({
              title: '修改角色异常',
              icon: 'none',
              mask: true
            })
          }

        }
      }
    })
  }
}
</script>

<style scoped lang="scss">
.MemberDetail{
  box-sizing: border-box;
  padding-bottom: constant(safe-area-inset-bottom);  ///兼容 IOS<11.2/
  padding-bottom: env(safe-area-inset-bottom);  ///兼容 IOS>11.2/
  .form-group+.form-group{
    border-top: 1upx solid #eee;
  }
}
</style>
